﻿namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Net.Mime;
    using System.Text;
    using System.Web.Mvc;
    using System.Xml;
    using SimpleWebServices;

    public sealed class XmlSerializationResult : ContentResult
    {
        public XmlSerializationResult()
            : this("application/xml", null as object)
        {
        }

        public XmlSerializationResult(string contentType, object model)
        {
            if (null == contentType)
            {
                throw new ArgumentNullException("contentType");
            }
            else if (0 == contentType.Length)
            {
                throw new ArgumentOutOfRangeException("contentType");
            }

            this.ContentEncoding = Encoding.UTF8;
            this.ContentType = new ContentType(contentType).MediaType;
            if (null != model)
            {
                XmlDocument xml = model.Serialize() as XmlDocument;
                xml.CreateXmlDeclaration("1.0", "utf-8", null);
                xml.PreserveWhitespace = false;

                this.Content = xml.OuterXml;
            }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (null == context)
            {
                throw new ArgumentNullException("context");
            }

            base.ExecuteResult(context);
        }
    }
}